﻿
using Module.FlowChart.RunAble.Code.View;
using System;
using System.Collections.Generic;

namespace Module.FlowChart.RunAble.Code
{
    internal class ConsoleManager
    {
        static ConsoleManager m_Instance;
        static public ConsoleManager Instance
        {
            get
            {
                return m_Instance ?? (m_Instance = new ConsoleManager());
            }
        }
        Form_Console m_form;
        Form_Console form
        {
            get
            {
                if (m_form == null || m_form.IsDisposed)
                {
                    m_form = new Form_Console();
                    m_form.OnInput += (d) =>
                    {
                        lock (this)
                        {
                            Cache.Enqueue(d);
                            OnInput?.Invoke();
                        }
                    };
                }
                return m_form;
            }
        }
        Queue<double> Cache = new Queue<double>();

        public Action OnInput;

        public void InitAndShow(Action OnInput = null, System.Drawing.Point? pos = null)
        {
            lock (this)
            {
                this.OnInput = OnInput;
                CacheClear();
                form.Clear();
                form.Show();
                if (pos != null)
                {
                    form.Location = pos.Value;
                }
            }
        }
        public System.Drawing.Size GetConsoleSize()
        {
            return form.Size;
        }
        public void Hide()
        {
            lock (this)
            {
                form?.Hide();
                CacheClear();
            }
        }
        public void WriteLine(object obj)
        {
            lock (this)
            {
                string s = obj.ToString();
                if (form.IsEndWithEnter)
                {
                    form.Append(s);
                    form.Append("\n");
                }
                else
                {
                    form.Append("\n");
                    form.Append(s);
                    form.Append("\n");
                }
            }
        }
        public void Write(object obj)
        {
            lock (this)
            {
                string s = obj.ToString();
                form.Append(s);
            }
        }
        public void Clear()
        {
            lock (this)
            {
                form.Clear();
            }
        }

        public bool IsCacheEmpty()
        {
            lock (this)
            {
                return Cache.Count == 0;
            }
        }
        public double CacheGet()
        {
            lock (this)
            {
                return Cache.Dequeue();
            }
        }
        public void CacheClear()
        {
            lock (this)
            {
                Cache.Clear();
            }
        }
    }
}
